<template>
	<view>
		<!-- ，开关开启时，新人首充优惠充值弹窗图片提醒 -->
		<view v-if="xrsc.xrscState">
			<aui-poster ref="poster" :mask="auiPoster.mask" :maskTapClose="auiPoster.maskTapClose"
				:image="auiPoster.pic" @callback="auiPosterCallback"></aui-poster>
		</view>

		<!-- 营销活动弹窗图片提醒 -->
		<aui-poster ref="poster2" :mask="index_activity.mask" :maskTapClose="index_activity.maskTapClose"
			:image="index_activity.pic" @callback="index_activity_Callback"></aui-poster>


		<view style="margin: 15rpx 20rpx 0 20rpx;" v-if="vk.vuex.get('$app.appinfo.opensearch')">
			<u-search placeholder="输入剧名搜索" v-model="keyword" @search="search" @custom="search"></u-search>
		</view>

		<view class="swiper">
			<u-swiper height="375rpx" indicator indicatorMode="dot" interval="8000" :list="swiperList" keyName="image"
				@click="dianjilunbo"></u-swiper>
		</view>

		<!-- 首页导航栏图标自定义组件navbar -->
		<djnavbar :iconList="iconList"></djnavbar>

		<!-- 视频列表自定义组件 -->
		<videolist :videoList="videoList"></videolist>

		<view class="positionStyle">
			<u-transition :show="!continueShow&& last_view.tv_image && index_activity.record_switch" mode="slide-left"
				duration="1000">
				<view class="continue-bg1">
					<view class="continue-border" @click="toVideoDetail(last_view)">
						<image class="continue-pic" :src="last_view.tv_image"></image>
						<text class="continue-text">继续观看</text>
					</view>
				</view>
			</u-transition>
		</view>



		<!-- <image v-if="showdingyue && index_activity.xjqxk_switch" class="fixed_pic1" @click="dingyue"
			:src="index_activity.xjqxk_pic"></image> -->

		<image v-if="!todaySign && index_activity.signin_switch" class="fixed_pic2" @click="tosign"
			:src="index_activity.signin_pic">
		</image>

	</view>
</template>

// <script>
	import aui from '@/components/aui-poster/common/aui/js/aui.js';
	import auiPoster from '@/components/aui-poster/aui-poster.vue';
	//不可直接命名navbar，会导致奇怪的报错，改名djnavbar
	import djnavbar from '@/components/navbar/navbar.vue';
	import videolist from '@/components/videolist/videolist.vue';
	import newslist from '@/components/newslist/newslist.vue';
	const db = uniCloud.database();
	const _ = db.command;
	export default {
		components: {
			auiPoster, //弹窗组件
			djnavbar, //导航栏组件
			videolist, //视频列表组件
			newslist, //资讯列表组件
		},
		data() {
			return {
				keyword: "",
				kefuurl: "",
				//首页营销活动
				index_activity: {
					mask: true,
					maskTapClose: false,
					pic: '',
				},
				//新人首充优惠弹窗
				auiPoster: {
					mask: true,
					maskTapClose: false,
					pic: 'https://saas-1257028257.cos.ap-nanjing.myqcloud.com/hediankj/indexpic.png'
				},
				showdingyue: true,
				todaySign: false,
				xrsc: {}, //新人首充配置信息
				showIndexCoupou: false, //是否展示首页弹窗优惠券
				page: 1,
				scrollTop: 0,
				lastscrollTop: 0,
				continueShow: false,
				indexTab: '精选',
				News: [],
				Contribute: [],
				Stills: [],
				last_view: {
					tv_image: '',
				},
				continueStyle: {
					left: '-120rpx',
				},
				tabList: [{
						name: '精选'
					},
					{
						name: '资讯'
					},
					{
						name: '网友投稿'
					},
					{
						name: '精美剧照'
					}
				],

				iconList: [],

				swiperList: [],
				videoList: [],
				awemeId: "56038861989",
			}
		},
		onShareAppMessage() {
			console.log("触发分享");
			//带上个人邀请码转发
			return {
				title: '', // 默认为小程序名称
				path: '/pages/index/index?invite_code=' + vk.vuex.get('$user.userInfo.my_invite_code'),
				imageUrl: '' // 默认为当前页面的截图
			}
		},
		async onLoad(options) {

			this.switch_page(options) //根据参数来判断应该进入哪个页面
			this.loadAppData() //加载APP数据，用户未登录也可以获取
			//设置定时器，监听页面滑动
			setInterval(() => {
				if (this.scrollTop == this.lastscrollTop) {
					this.continueShow = false
				} else {
					this.continueShow = true
				}
				this.lastscrollTop = this.scrollTop
			}, 400)
		},
		async onShow() {
			this.showIndexCoupou = vk.vuex.get('$app.showIndexCoupou') || false
			let had_youhui = vk.vuex.get('$user.userInfo.had_youhui')
			//首页弹窗开关开启且未享受过充值优惠，弹出首页广告
			if (this.showIndexCoupou && !had_youhui) {
				this.$refs.poster.show();
			}
			console.log("invite:", uni.getStorageSync('invite_code'));

			let uid = vk.vuex.get('$user.userInfo._id');

			// vk存在删除用户问题，故 使用下列方式
			await uni.vk.myfn.ttlogin();
			// 延时1000，防止vk登陆缓存未完成
			setTimeout(async () => {
				await this.load_recharge()
				await this.loadUserData()
			}, 1000)


		},

		onPageScroll(e) {
			this.scrollTop = Math.trunc(e.scrollTop)
		},

		async onReachBottom() {
			var that = this;
			console.log("触底了this.page=", this.page)
			if (this.indexTab == "精选") {
				vk.callFunction({
					url: 'client/pages/pub/index_videolist',

					data: {
						appid: vk.vuex.get('$app.appid'),
						page: that.page
					},
					success: (data) => {
						that.videoList = that.videoList.concat(data.videoList)
						that.page = that.page + 1;
					}
				});
				return;
			}

			vk.callFunction({
				url: 'client/pages/pub/index_newslist',
				data: {
					type: "onReachBottom",
					appid: vk.vuex.get('$app.appid'),
					indexTab: this.indexTab,
					page: this.page
				},
				success: (data) => {
					if (that.indexTab == "资讯") {
						that.News = that.News.concat(data.newslist)
						that.page = that.page + 1;
					}
					if (that.indexTab == "网友投稿") {
						that.Contribute = that.Contribute.concat(data.newslist)
						that.page = that.page + 1;
					}
					if (that.indexTab == "精美剧照") {
						that.Stills = that.Stills.concat(data.newslist)
						that.page = that.page + 1;
					}
				}
			});
		},
		methods: {
			search() {
				if (!this.keyword) {
					vk.toast('搜索词不能为空')
					return;
				}
				uni.navigateTo({
					url: "/pages/index/search?keyword=" + this.keyword
				})
			},

			load_recharge() {
				vk.callFunction({
					url: 'client/pay/kh/get_rechargelist',
					// title: '请求中...',
					data: {
						appid: vk.vuex.get('$app.appid')
					},

					success: (data) => {
						setTimeout(() => {
							uni.vk.vuex.set('$app.rechargelist', data.recharge)
						}, 0)

					}
				});
			},
			check_invite_code(userInfo) {
				//检查是否开启静态化邀请码。即用户注册后邀请码始终不变。默认开启
				//特别注意：当参数类型为布尔值时，不可使用缺省值。否则布尔值为false时会自动使用缺省值
				let staticInvite_code = vk.vuex.get('$app.appinfo.staticInvite_code');
				if (staticInvite_code) {
					//如果开启静态化邀请码动态化，直接return;
					return;
				}
				//检查最新的invite_code和tfid,如果有变化就更新用户信息。0则直接return
				let local_invite_code = uni.getStorageSync('invite_code') || 0;
				let local_tfid = uni.getStorageSync('tfid') || 0;
				if (!local_invite_code || !local_tfid) {
					return;
				}
				if (userInfo.invite_code != local_invite_code ||
					userInfo.tfid != local_tfid) {
					vk.callFunction({
						url: 'client/user/kh/update_userinfo',
						// title: '请求中...',
						data: {
							invite_code: local_invite_code,
							tfid: local_tfid
						},
						success: (data) => {

						}
					});
				}
			},
			async loadAppData() {
				vk.callFunction({
					url: 'client/pages/pub/index_appdata',
					data: {
						appid: vk.vuex.get('$app.appid')
					},
					success: (res) => {
						// vk.hideLoading();
						console.log("vkres:", res);
						this.videoList = res.videoList; //首页推荐视频
						this.swiperList = res.swiperList; //首页轮播图
						this.auiPoster.pic = res.indexpic; //首页弹窗图片
						this.index_activity = res.active; //首页弹窗活动(每次进入都弹)
						vk.vuex.set('$app.index_activity', res.active);
						vk.vuex.set('$app.dykefu', res.dykefu.dykefu);
						this.xrsc = res.xrsc; //新人首充配置信息

						uni.setStorageSync("dataList", res.dataList); //推荐视频数据放到缓存
						vk.vuex.set('$app.ucenter_icons', res.ucenter_icons) //个人中心导航图标
						//当找到对应数据时，替换掉默认数据
						if (res.index_icons.length > 0) {
							this.iconList = []
							this.iconList = res.index_icons
						}
						//active开关值为true，则直接弹窗
						if (res.active.status) {
							this.$refs.poster2.show();
						}
					}
				});
			},
			loadUserData() {
				vk.callFunction({
					url: 'client/pages/kh/index_userdata',
					data: {
						todatStart: vk.vuex.get('$app.time.todayStart'),
					},
					success: (res) => {
						// console.log("vkres:", res);
						this.todaySign = res.todaySign;
						this.last_view = res.last_view;
						this.check_uservip(res.userInfo)
					}
				});
			},
			async check_uservip(userInfo) {
				if (userInfo.plus_type == 0) {
					console.log("用户非会员");
					return;
				}
				//判断用户的会员到期没有，到期的话就把plus_type改为0
				let plus_type = userInfo.plus_type
				let plus_expire_time = userInfo.plus_expire_time
				let nowtime = new Date().getTime()
				if (plus_expire_time < nowtime && plus_type == 1) {
					console.log("用户会员已过期，改为普通用户");
					let updateVip = await db.collection('uni-id-users').doc(userInfo._id).update({
						plus_type: 0
					})
				}
			},
			async switch_page(options) {
				if (options.path == "player") {
					const tv_info = await db.collection('a_tv').doc(options.tv_id).get()
					console.log("options:", tv_info.result.data[0]);
					//参数带来的series需要传过去
					tv_info.result.data[0].series = options.series;
					this.toVideoDetail(tv_info.result.data[0])
				}

				if (options.path == "record") {
					//自动加载用户的最后一条历史浏览记录，并进入播放
					const last_view = await db.collection('a_history').where({
						user_id: vk.vuex.get('$user.userInfo._id')
					}).orderBy('_add_time', 'desc').limit(1).get()

					this.toVideoDetail(last_view.result.data[0])
				}

				if (options.path == "signin") {
					uni.navigateTo({
						url: "/pages_sub/signin/signin"
					})
				}
				if (options.path == "freeReceive") {
					uni.navigateTo({
						url: "/pages_sub/freeReceive/freeReceive"
					})
				}
			},
			async toVideoDetail(item) {
				if (item.tv_id) {
					let temp_series = item.series || 1;
					const tvinfo = await db.collection('a_tv').doc(item.tv_id).get()
					item = tvinfo.result.data[0]
					item.series = temp_series;
				}
				vk.vuex.set('$app.currenttv', item)
				uni.navigateTo({
					url: '/pages/player/player?tv_id=' + item._id + "&series=" + item.series
				})
			},
			tosign() {
				uni.navigateTo({
					url: "/pages_sub/signin/signin"
				})
			},

			//复制邮箱
			copyemail() {
				uni.setClipboardData({
					data: vk.vuex.get('$app.appinfo.tgemail'),
					success() {
						uni.showToast({
							title: "邮箱复制成功"
						})
					}
				})
			},


			dianjilunbo(e) {
				vk.pubfn.debounce(() => {
					this.clickSwiper(e)
				}, 2000);

			},



			//轮播图点击
			clickSwiper(e) {
				if (this.swiperList[e].url) {
					vk.navigateTo(this.swiperList[e].url);
					return;
				} else {
					this.toVideoDetail(this.swiperList[e])
				}
			},

			//点击新人首充弹窗优惠
			auiPosterCallback(e) {
				console.log("e", e);
				if (e.type == "main") {
					vk.vuex.set('$app.showIndexCoupou', false)
					uni.navigateTo({
						url: "/pages_sub/recharge/discount?from=index"
					})
				}
			},

			//点击首页营销活动弹窗
			index_activity_Callback(e) {
				if (e.type == "main") {
					uni.navigateTo({
						url: this.index_activity.jump_url
					})
				}
			},

			async clickTab(item) {
				var that = this;
				this.page = 1
				this.indexTab = item.name

				var indexTab = this.indexTab;
				if (this.indexTab == "资讯") {
					indexTab = "短剧资讯"
				}
				if (this.indexTab == "精选") {
					indexTab = "精选短剧"
				}
				vk.callFunction({
					url: 'client/pages/pub/index_newslist',

					data: {
						type: "onload",
						appid: vk.vuex.get('$app.appid'),
						indexTab: indexTab,
					},
					success: (data) => {
						if (that.indexTab == "资讯") {
							that.News = [];
							that.News = that.News.concat(data.newslist)
						}
						if (that.indexTab == "网友投稿") {
							that.Contribute = [];
							that.Contribute = that.Contribute.concat(data.newslist)
						}
						if (that.indexTab == "精美剧照") {
							that.Stills = [];
							that.Stills = that.Stills.concat(data.newslist)
						}
					}
				});
				// vk.hideLoading()
			},

			jump(url) {
				if (url == "kefu") {
					wx.openCustomerServiceChat({
						extInfo: {
							url: vk.vuex.get('$app.appinfo.workwxurl'),
						},
						corpId: vk.vuex.get('$app.appinfo.workwxappid'),
						success(res) {
							调用客服成功
						}
					})
					return;
				}
				if (url == "/pages/Tabbar/watching/watching" || url == "/pages/Tabbar/tj/tj" || url ==
					"/pages/my/my") {
					uni.switchTab({
						url: url
					})
					return;
				}
				if (url == "/pages/index/index" || url == "/pages/Tabbar/my/my") {
					uni.switchTab({
						url: url
					})
					return;
				}
				uni.navigateTo({
					url: url
				})
			},

			dingyue() {
				var that = this;
				uni.requestSubscribeMessage({
					tmplIds: vk.vuex.get('$app.msglist'),
					success(res) {
						console.log("订阅成功");
						uni.showToast({
							title: "操作成功"
						})
						that.showdingyue = false
						vk.callFunction({
							url: 'client/user/kh/dingyue',
							// showLoading: false,
							data: {
								msglist: vk.vuex.get('$app.msglist'),
								platform: "weixin",
								tv_id: "no",
								tv_name: "no"
							},
						})
					},
					fail() {
						that.showdingyue = true
					}
				})
			},

			jumpDetail_wy(id) {
				uni.navigateTo({
					url: '/pages_sub/detail_wy/detail_wy?id=' + id
				})
			}

		}
	}
</script>

<style>
	.positionStyle {
		position: fixed;
		bottom: 50rpx;
		/* width: 100% */
	}

	.transition {
		background-color: aqua;
		width: 200rpx;
		height: 400rpx;
	}

	.fixed_pic1 {
		position: fixed;
		bottom: 120rpx;
		right: 10rpx;
		width: 180rpx;
		height: 180rpx;
	}


	.fixed_pic2 {
		position: fixed;
		bottom: 20rpx;
		right: 50rpx;
		width: 100rpx;
		height: 100rpx;
		border-radius: 20rpx;
	}

	/* 精选 */
	.swiper {
		margin: 30rpx 20rpx 30rpx 20rpx;
	}

	.continue-border {
		border: 3rpx solid #7d5f40;
		width: 165rpx;
		height: 237rpx;
		border-radius: 15rpx;
		background-color: aqua;
		background-color: #f2c351;
		padding: 10rpx;
		border-radius: 20rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.continue-pic {
		border-radius: 11rpx;
		width: 165rpx;
		height: 247rpx;
		z-index: 999;
	}

	.continue-text {
		position: absolute;
		color: #000000;
		background-color: #fddd94;
		font-size: 24rpx;
		width: 125rpx;
		text-align: center;
		left: 30rpx;
		top: 200rpx;
		z-index: 999;
		border: 2rpx solid #fff8ce;
		border-radius: 8rpx;
	}

	.continue-bg1 {
		background-color: #d7893e;
		padding: 0 0 10rpx 0;
		width: 188rpx;
		border-radius: 20rpx;
		border: 2rpx solid #7d5f40;
	}

	/* 网友投稿 */
	.Contribute_box {
		margin-top: 20rpx;
		display: flex;
		justify-content: space-evenly;
	}

	.Contribute_image {
		width: 340rpx;
		height: 200rpx;
		border-radius: 10rpx;
	}

	.text_box {
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		margin: 10rpx 0;
	}

	.Contribute_author1 {
		font-size: 30rpx;
		width: 340rpx;
		display: -webkit-box;
		overflow: hidden;
		white-space: normal !important;
		text-overflow: ellipsis;
		word-wrap: break-word;
		-webkit-line-clamp: 1;
		-webkit-box-orient: vertical;
	}

	.Contribute_author2 {
		font-size: 26rpx;
		width: 160rpx;
		display: -webkit-box;
		overflow: hidden;
		white-space: normal !important;
		text-overflow: ellipsis;
		word-wrap: break-word;
		-webkit-line-clamp: 1;
		-webkit-box-orient: vertical;
	}

	.gzh {
		position: fixed;
		bottom: 60rpx;
		background-color: #EFA029;
		color: #ffffff;
		width: 700rpx;
		font-size: 32rpx;
		margin-left: 15rpx;
		/* text-align: center; */
		border-radius: 60rpx;
		padding: 14rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
</style>